package cn.wx.scholar.neo4j.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import cn.wx.common.persistence.exception.MyException;
import cn.wx.common.persistence.web.ResponseCode;
import cn.wx.scholar.core.entity.Social;
import cn.wx.scholar.core.entity.qo.SocialQ;
import cn.wx.scholar.core.service.SocialService;
import cn.wx.scholar.neo4j.entity.Neo4jSocial;
import cn.wx.scholar.neo4j.entity.qo.Neo4jSocialQ;
import cn.wx.scholar.neo4j.repository.SocialRepository;

@Service
public class Neo4jSocialService {
	
	@Autowired
	private SocialService socialService;
	
	@Autowired
	private SocialRepository socialRepository;
	
	/**
	 * 查看新闻详情功能
	 * @return
	 */
	public Neo4jSocial findOneSocial(Long id) {
		Optional<Neo4jSocial> nws = socialRepository.findById(id);
		Neo4jSocial nw = nws.get();
		if(nw != null) {
			SocialQ nQ = new SocialQ();
			nQ.setfId(nw.getfId());
			Social social = socialService.queryUnique(nQ, Social.class);
			
			if(social != null) {
				nw.setText(social.getTextSrc_());
			}
		}
		return nw;
	}
	
	
	
	public Page<Neo4jSocial> findAllSocialByExpertId(Neo4jSocialQ neo4jSocialQ){
		
		/**
		 * 必要参数
		 */
		if(neo4jSocialQ == null || neo4jSocialQ.getExpertId() == null) {
			throw new MyException(ResponseCode.PARAMETER_REQUIRED);
		}
		
		/**
		 * 知识图谱查询social
		 */
		Page<Neo4jSocial> pages = socialRepository
				.findAllSocialByExpertId(neo4jSocialQ.getExpertId(), 
						PageRequest.of(neo4jSocialQ.getPageSkip(), neo4jSocialQ.getPageSize()));
		
		/**
		 * 从mysql中查数据
		 */
		if(pages!=null && pages.getContent()!=null) {
			
			List<Long> nids = new ArrayList<>();
			
			for(Neo4jSocial ew : pages.getContent()) {
				nids.add(ew.getfId());
			}
			if(nids != null && nids.size() > 0 ) {
				
				SocialQ nQ = new SocialQ();
				nQ.setfIds(nids);
				List<Social> cSocials = socialService.queryList(nQ);
				
				Map<Long,String> cNewsMap = null;
				
				if(cSocials != null && cSocials.size() > 0) {
					cNewsMap = new HashMap<>();
					for(Social n : cSocials) {
						cNewsMap.put(n.getfId(), n.getTextSrc_());
					}
				}
				
				if(cNewsMap != null) {
					for(Neo4jSocial ew_ : pages.getContent()) {
						ew_.setText(cNewsMap.get(ew_.getfId()));
					}
				}
			}
	
		}
		return pages;
    }
}
